﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Security.Permissions;
using System.Text;
using System.Windows.Forms;
using WeatherLib;
using WeatherUSB;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Weather
{
    [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    [System.Runtime.InteropServices.ComVisibleAttribute(true)]
    public partial class frmMain : Form
    {
        private Bitmap m_PrintImg = null;
        private PrintDocument m_PrintDocument = null;
        private bool m_AddWidth = false;

        private USBLib _USBLib = new USBLib();
        private WeatherDataLib _WeatherDataLib = new WeatherDataLib();
        private SetupLib _SetupLib = new SetupLib(AppGlobal.CurrentDirectory);

        public frmMain()
        {
            InitializeComponent();
            FormBorderStyle = FormBorderStyle.None;
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            //            wbMain.Url = new Uri(string.Format("{0}\\{1}", AppGlobal.CurrentDirectory, "TestCS.html"));
#if DEBUG
            var u = new Uri(@"D:\Source Code\PartTime\Weather\Code\Weather2.0\WeatherFlash\bin-debug\Weather.html");
#else
             var u = new Uri(string.Format("{0}\\{1}", AppGlobal.CurrentDirectory, "Weather.html"));
#endif

            wbMain.Url = u;
            wbMain.ObjectForScripting = this;

            Height = 164;
            Width = 283;

            //            MessageBox.Show(string.Format("{0},{1}", Height, Width));

            if (Screen.PrimaryScreen.WorkingArea.Height < Height)
            {
                /*Top = -(SystemInformation.CaptionHeight);
                if (Screen.PrimaryScreen.WorkingArea.Height + SystemInformation.CaptionHeight < Height)
                {
                    Top -= 20;
                    if (Screen.PrimaryScreen.WorkingArea.Height + SystemInformation.CaptionHeight + 20 < Height)
                    {
                        Top = Top - (Height - (Screen.PrimaryScreen.WorkingArea.Height + SystemInformation.CaptionHeight + 20)) / 2;
                    }
                }*/
                Height = Screen.PrimaryScreen.WorkingArea.Height;
                Width += 30;
                m_AddWidth = true;
            }

            string tmpStr = LoadData.OpenUSB();
            if (!string.IsNullOrEmpty(tmpStr))
            {
                //                MessageBox.Show(tmpStr);
            }

            m_PrintImg = new Bitmap(wbMain.Width, wbMain.Height);
            m_PrintDocument = new PrintDocument();

            m_PrintDocument.PrintPage += PrintDocument_PrintPage;

            _USBLib.OpenUSBMsg = MainOpenUSBMsg;
        }

        private string MainOpenUSBMsg(string value)
        {
            return string.Empty;
        }

        private void frmMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            LoadData.CloseUSB();
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            _USBLib.SaveWeatherData();

            try
            {
            //    string result = wbMain.Document.InvokeScript("cs2js", new object[] { "closeForm", "" }).ToString();
            //    if (result.ToLower() == "true")
            //    {
            //        wbMain.Url = null;
            //        e.Cancel = true;
            //    }
            }
            catch (Exception)
            {
            }
        }

        private string _MainMsg = "";
        public string js2cs(string func, string msg)
        {
            string result = string.Empty;

            switch (func)
            {
                case "ExitApp":
                    result = "OK ExitApp";
                    tExit.Enabled = true;
                    break;
                case "ResizeApp":
                    result = "OK ResizeApp";
                    _MainMsg = msg;
                    tResize.Enabled = true;
                    break;
                case "MinApp":
                    result = "OK MinApp";
                    WindowState = FormWindowState.Minimized;
                    break;
                case "GetTemperature":
                    result = _WeatherDataLib.GetTemperature(msg);
                    break;
                case "EnableUSB":
                    tUSBData.Enabled = true;
                    result = "OK USB";
                    break;
                case "SaveTools":
                    result = _SetupLib.SaveTools(msg);
                    break;
                case "LoadTools":
                    result = _SetupLib.LoadTools();
                    break;
            }
            return result;
        }

        private void InstallFlash()
        {
            string filename = Path.Combine(AppGlobal.CurrentDirectory, "flashplayer.exe");

            if (File.Exists(filename))
            {
                if (MessageBox.Show("Are you sure to install flash player", "information", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    var p = new Process();
                    p.StartInfo.FileName = filename;
                    p.Start();
                    p.WaitForExit();

                    wbMain.Refresh();
                }
            }
        }

        private void PrintApp()
        {
            var ps = GetPrintNames();

            if (ps == null && ps.Count == 0)
            {
                MessageBox.Show("No printer");
                return;
            }
            m_PrintDocument.DefaultPageSettings.Landscape = true;
            Graphics g = Graphics.FromImage(m_PrintImg);

            int printWidth = wbMain.Width;
            int printHeight = wbMain.Height;
            if (m_AddWidth)
            {
                printWidth -= 30;
            }

            g.CopyFromScreen(wbMain.PointToScreen(wbMain.Location), new Point(0, 0), new Size(printWidth, printHeight));
            IntPtr dc1 = g.GetHdc();
            g.ReleaseHdc(dc1);

            var pf = new frmPrint();
            pf.GetPrintNames = ps;

            if (pf.ShowDialog() == DialogResult.OK)
            {
                if (!string.IsNullOrEmpty(pf.PrinterName))
                {
                    m_PrintDocument.PrinterSettings.PrinterName = pf.PrinterName;
                    m_PrintDocument.Print();
                }
                else
                {
                    MessageBox.Show("No printer");
                }
            }
        }

        void PrintDocument_PrintPage(object sender, PrintPageEventArgs e)
        {
            m_PrintDocument.DefaultPageSettings.Landscape = true;
            int printWidth = m_PrintImg.Width;
            int printHeight = m_PrintImg.Height;

            if (e.PageBounds.Width < printWidth)
            {
                printHeight = (int)(printHeight * ((double)e.PageBounds.Width / printWidth));
                printWidth = e.PageBounds.Width;
            }
            else if (e.PageBounds.Height < printHeight)
            {
                printWidth = (int)(printWidth * ((double)e.PageBounds.Height / printHeight));
                printHeight = e.PageBounds.Height;
            }

            int printX = (e.PageBounds.Width - printWidth) / 2;
            int printY = (e.PageBounds.Height - printHeight) / 2;


            e.Graphics.DrawImage(m_PrintImg, printX, printY, printWidth, printHeight);
        }

        /// <summary>   
        /// 获取本机默认打印机名称   
        /// </summary>   
        private String DefaultPrinter
        {
            get { return m_PrintDocument.PrinterSettings.PrinterName; }
        }

        /// <summary>   
        /// 获取本机的打印机列表。列表中的第一项就是默认打印机。   
        /// </summary>   
        private List<string> GetPrintNames()
        {
            List<String> fPrinters = new List<string>();
            fPrinters.Add(DefaultPrinter); // 默认打印机始终出现在列表的第一项   
            foreach (String fPrinterName in PrinterSettings.InstalledPrinters)
            {
                if (!fPrinters.Contains(fPrinterName))
                    fPrinters.Add(fPrinterName);
            }
            return fPrinters;
        }

        private void wbMain_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {

        }

        private void tExit_Tick(object sender, EventArgs e)
        {
            tExit.Enabled = false;
            Application.Exit();
        }

        private void tResize_Tick(object sender, EventArgs e)
        {
            if(!string.IsNullOrEmpty(_MainMsg))
            {
                JObject o = JObject.Parse(_MainMsg);
                //o.HasValues
                if (o["width"] != null && o["height"] != null)
                {
                    Width = (int)o["width"];
                    Height = (int)o["height"];

                    int height = System.Windows.Forms.SystemInformation.WorkingArea.Height;
                    int width = System.Windows.Forms.SystemInformation.WorkingArea.Width;

                    int formheight = Height;
                    int formwidth = Width;

                    int newformx = width / 2 - formwidth / 2;
                    int newformy = height / 2 - formheight / 2;

                    this.SetDesktopLocation(newformx, newformy);
                }
                //_MainMsg

                _MainMsg = string.Empty;
            }
        }

        private void wbMain_FileDownload(object sender, EventArgs e)
        {
            wbMain.ScrollBarsEnabled = false;
        }

        private void tUSBData_Tick(object sender, EventArgs e)
        {
            string result = wbMain.Document.InvokeScript("cs2js", new object[]
            {
                "USBData", _USBLib.GetNowData()
            }).ToString();

        }
    }
}
